package cn.hd01.sms.ucp;

import java.util.Date;

import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import cn.hd01.sms.SmsService;
import cn.hd01.sms.web.SmsController;
import cn.hd01.util.HttpClientHelper;
import cn.hd01.util.MD5Util;

@Service
public class UCPSmsService implements SmsService {
	private Logger logger = LoggerFactory.getLogger(UCPSmsService.class);
	
	@Value("${ucp.url}")
	private String url;

	@Value("${ucp.appid}")
	private String appid;

	@Value("${ucp.sid}")
	private String sid;

	@Value("${ucp.token}")
	private String token;

	@Value("${ucp.templateId}")
	private String templateId;

	@Override
	public boolean send(String mobile, String code) {
		String time = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
		String sig = getSig(time);
		String auth = getAuthorization(time);

		String body = "{\"templateSMS\":{\"appId\": \"" + appid + "\",\"param\":\"" + code + "\",\"templateId\":\""
				+ templateId + "\",\"to\":\"" + mobile + "\"}}";

		logger.info("send code {} to {} ", code, mobile);
		String resp = HttpClientHelper.instance().postJson(url + "?sig=" + sig, body, auth);
		logger.info("response from ucp is  ", resp);
		return true;
	}

	private String getSig(String time) {
		return MD5Util.encode(sid + token + time).toUpperCase();
	}

	private String getAuthorization(String time) {
		return Base64Utils.encodeToString((sid + ":" + time).getBytes());
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}

	public void setAppid(String appid) {
		this.appid = appid;
	}

}
